package com.huiminpay.merchant.global;

import com.huiminpay.common.cache.domain.BusinessException;
import com.huiminpay.common.cache.domain.CommonErrorCode;
import com.huiminpay.common.cache.domain.ErrorCode;
import com.huiminpay.common.cache.domain.RestErrorResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@ControllerAdvice
@Slf4j
public class GlobalException {

    @ResponseBody
    @ExceptionHandler(value = BusinessException.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public RestErrorResponse restErrorResponse(BusinessException businessException) {
        ErrorCode errorCode = businessException.getErrorCode();
        businessException.printStackTrace(); //打印错误
        return new RestErrorResponse(errorCode.getCode() + "", errorCode.getDesc());
    }

    //捕获Exception异常
    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public RestErrorResponse processExcetion(Exception e) {
        //解析异常信息
        //如果是系统自定义异常，直接取出errCode和errMessage
//        if(e instanceof BusinessException){
//            log.info(e.getMessage(),e);
//            //解析系统自定义异常信息
//            BusinessException businessException= (BusinessException) e;
//            ErrorCode errorCode = businessException.getErrorCode();
//            //错误代码
//            int code = errorCode.getCode();
//            //错误信息
//            String desc = errorCode.getDesc();
//            return new RestErrorResponse(String.valueOf(code),desc);
//        }

        log.error("系统异常：", e);
        e.printStackTrace();
        //统一定义为99999系统未知错误
        return new RestErrorResponse(String.valueOf(CommonErrorCode.UNKOWN.getCode()), CommonErrorCode.UNKOWN.getDesc());

    }
}
